//
//  HTFrameNet.m
//  page51学习集合_Nav
//
//  Created by standychen on 14-11-4.
//  Copyright (c) 2014年 HT. All rights reserved.
//

#import "HTFrameNet.h"
#import "HTFrameKit.h"
#import "HTFrameAlert.h"
#import "AFNetworking.h"
//#import "AFNetworking-master/AFNetworking/AFNetworking.h"
#import "JSONKit.h"
//#import "JSONKit-master/JSONKit.h"
#import "ASIFormDataRequest.h"

//全局变量  服务地址 暂时无法使用 待研究
//static NSMutableString *ServerUrl;

static NSString *_defaultServerUrl=@"192.168.1.111";
static NSString *_defaultServerVir=@"htapppt";//虚拟目录


@implementation HTFrameNet

//默认服务器地址设置
+(void)defaultServerUrlSet:(NSString *)str{
    _defaultServerUrl=str;
}
//默认服务器虚拟目录设置，一般不使用
+(void)defaultServerVirSet:(NSString *)str
{
    _defaultServerVir=str;
    
}

//默认初始化
-(HTFrameNet *)init
{
    if(self==[super init])
    {
        NSString *setUrl=[[NSString alloc] initWithFormat:@"http://%@/%@/",_defaultServerUrl,_defaultServerVir];
        self.ServerUrl=[[NSMutableString alloc]initWithString: setUrl];// http://58.210.191.210:199
    }
    return self;
}


//带URL的初始化
-(HTFrameNet *)initWithServerUrl:(NSString *)serverUrl
{
    
    if(self==[super init])
    {
        self.ServerUrl=[[NSMutableString alloc]initWithString: serverUrl];
    }
    return self;
}

//获得服务器默认地址
+(NSString *)hmGetServerUrl{
    NSString *setUrl=[[NSString alloc] initWithFormat:@"http://%@/%@/",_defaultServerUrl,_defaultServerVir];
    return setUrl;
}

#pragma mark --接收的WCF字符串转换为为json字符串；因为接收到的字符是前后多了双引号；用到转义反斜杠字符的都是反斜杠表示的
-(NSString *)hmConvertJsonStrFromWCF:(NSString *)receiveStr
{
    NSString *result=[receiveStr copy];//[[NSString alloc]initWithString:receiveStr];
    
    if([receiveStr length]>0)//字符串长度有值
    {
        NSMutableString *strmul=[[NSMutableString alloc] initWithString:receiveStr];//转换为可变字符串
    
        NSRange rangek = NSMakeRange(0, [strmul length]);//检查范围，整个字符串
    
        [strmul replaceOccurrencesOfString:@"\\\"" withString:@"\"" options:NSCaseInsensitiveSearch range:rangek];  //把\"替换为\
        
        rangek = NSMakeRange(0, [strmul length]);//检查范围，整个字符串
        [strmul replaceOccurrencesOfString:@"\\\/" withString:@"\/" options:NSCaseInsensitiveSearch range:rangek];  //把\/替换为/
        
        if([strmul length]>=2)
        {
            NSRange rangek2 = NSMakeRange(1, [strmul length]-2);//去掉一头一尾两个字符
            NSString *strconvert= [strmul substringWithRange:rangek2];
            result =strconvert;
        }
    }
    return result;
}

//访问NET服务并返回结果JSON字符串，如果错误返回NULL字符串，不执行操作
//使用AFHTTPRequestOperationManager
//传入类名+方法名；参数字典；处理返回结果的代码块
//异步访问
-(void)hmNetWCFmethodName:(NSString *)methodName andDic:(NSDictionary *)dict complete:(void(^)(NSString *backstr))block
{
    //0.准备地址
    NSString *urlASString=[[NSString alloc] initWithFormat:@"%@%@",self.ServerUrl,methodName];
    //urlASString = [urlASString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
    
    //1.管理器
    AFHTTPRequestOperationManager *manager =[AFHTTPRequestOperationManager manager];
    
    //2.设定类型. (这里要设置request-response的类型)
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer]; //这个决定了下面responseObject返回的类型
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"charset=utf-8", nil];
    //3.发送请求
    [manager POST:urlASString parameters:dict success: ^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *resultstr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
       
        //转换为json字符串
        NSString *strconvert=[self hmConvertJsonStrFromWCF:resultstr];
        if ([self hmNetRootRecProc:strconvert]) {//执行成功才调用代码块
            
            if (block) block(strconvert);//调用代码块
        }
        
    } failure: ^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@", error);//异常错误
        //[HTFrameAlert hmAlertInfo:@"网络断开，请重新连接"];
        
    }];
    
    //[manager.operationQueue cancelAllOperations]; 释放资源
    
}





//访问NET服务并返回结果JSON字符串，如果错误返回NULL字符串，不执行操作
//使用ASI
//传入类名+方法名；参数字典；处理返回结果的代码块
//同步访问
-(void)hmNetASImethodName:(NSString *)methodName complete:(void(^)(NSString *backstr))block
{
    //0.准备地址
    NSString *urlASString=[[NSString alloc] initWithFormat:@"%@%@",self.ServerUrl,methodName];
    
    NSURL *url = [NSURL URLWithString:urlASString];
    ASIFormDataRequest *request = [[ASIFormDataRequest alloc]initWithURL:url];
    [request setRequestMethod:@"GET"];
    [request startSynchronous];//同步
    
    NSError *error = [request error];
    
    if (!error) {
        
        NSString *resultstr = [request responseString];
        
        
        //转换为json字符串
        NSString *strconvert=[self hmConvertJsonStrFromWCF:resultstr];
        if ([self hmNetRootRecProc:strconvert]) {//执行成功才调用代码块
            
            if (block) block(strconvert);//调用代码块
        }

        
    }
    else
    {
        
//        [self hmNetASImethodName:methodName complete:^(NSString *backstr){}];
        NSLog(@"%@", error);//异常错误
        NSLog(@"连接服务器超时，请重新点击登录！");
        //[self hmNetASImethodName:methodName complete:^(NSString *backstr){}];
        [HTFrameAlert hmAlertInfo:@"网络连接错误！"];
    }
}


//IOS自带访问网络同步处理代码
//同步
//待开发
-(void)hmNetIOSGetMethodName:(NSString *)methodName{
    
    
    //0.准备地址
    NSString *urlASString=[[NSString alloc] initWithFormat:@"%@%@",self.ServerUrl,methodName];
    //did 634
        //srvso/QueryFormdata
        
        
        NSURL *url=[NSURL URLWithString:urlASString];
        //创建request对象
        NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
        [request setHTTPMethod:@"GET"];
    NSURLResponse *response;//=[[NSURLResponse alloc] init];
    //NSError *errorConnection=[[NSError alloc]init];
    //[NSURLConnection sendSynchronousRequest:request returningResponse:response error:nil];
    //[NSURLConnection sendSynchronousRequest:<#(NSURLRequest *)#> returningResponse:<#(NSURLResponse *__autoreleasing *)#> error:(NSError *__autoreleasing *)];
    //[NSURLConnection sendSynchronousRequest:request returningResponse:response error:error];
    //[NSURLConnection sendAsynchronousRequest:<#(NSURLRequest *)#> queue:<#(NSOperationQueue *)#> completionHandler:<#^(NSURLResponse *response, NSData *data, NSError *connectionError)handler#>];

}

//IOS自带访问网络异步处理代码
//GET
//待开发
-(void)hmNetIOSGetAsynchMethodName:(NSString *)methodName{
    
    //0.准备地址
    NSString *urlASString=[[NSString alloc] initWithFormat:@"%@%@",self.ServerUrl,methodName];
    
    NSURL *url=[NSURL URLWithString:urlASString];
    //创建request对象
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    //[request setHTTPMethod:@"POST"];
    NSOperationQueue *queue=[NSOperationQueue mainQueue];//队列 取当前主队列
    
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if(connectionError!=nil)
        {
            NSLog(@"fail");
        }
        else
        {
            NSLog(@"success");
            //获取数据 data,需要转化成认识的结构
            NSString *jsonString=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"返回数据:%@",jsonString);
            
            
        }
        
    }];//异步请求
}


//处理标准根信息,返回成功与否标志，如果失败，直接进行信息提示
-(BOOL)hmNetRootRecProc:(NSString *)jsonStr
{
    NSDictionary *recdict=[HTFrameNet hmConvertDictFromJsonStr:jsonStr];//接收字典
    if(recdict !=nil){
        int flag=[[recdict objectForKey:kpNET_RETURN_error] intValue];
        if(flag==1){
            NSString *recmsg=[recdict objectForKey:kpNET_RETURN_MESSAGE];
            NSString *alertmsg=[[NSString alloc] initWithFormat:@"服务异常,代码%@",recmsg];
            [HTFrameAlert hmAlertInfo:alertmsg];
            return FALSE;
        }
    }
    
    return TRUE;
}


//转换数据库标题字符串为字典格式
+(NSDictionary *)hmConvertDictFromTitleStr:(NSString *)titleStr
{
    NSMutableString *strmul=[[NSMutableString alloc] initWithString:titleStr];//转换为可变字符串
    
    NSRange rangek = NSMakeRange(0, [strmul length]);//检查范围，整个字符串
    
    [strmul replaceOccurrencesOfString:@"'" withString:@"\"" options:NSCaseInsensitiveSearch range:rangek];  //把单引号替换为双引号
    
    NSString *jsonStr=[[NSString alloc]initWithString:strmul];
    return [self hmConvertDictFromJsonStr:jsonStr];
}


//转换json字符串为字典格式
+(NSDictionary *)hmConvertDictFromJsonStr:(NSString *)jsonStr
{
    jsonStr=[[NSString alloc]initWithFormat:@"{%@}",jsonStr ];
    NSData* jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *resultDict = [jsonData objectFromJSONData];                                             
    return resultDict;
}


+(NSArray *)hmConvertArrFromJsonStr:(NSString *)jsonStr{
    
    NSData* jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    NSArray *arrlist=[jsonData objectFromJSONData];
    return  arrlist;
}


//转换json字符串为数组
+(NSMutableArray *)hmConvertArrayFromJsonStr:(NSString *)jsonStr
{
    NSData* jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    NSArray *arrlist=[jsonData objectFromJSONData];
    NSMutableArray *arrconvert=[[NSMutableArray alloc] init];
    for (int i=0; i<[arrlist count]; i++) {
        [arrconvert addObject:(NSString *)[arrlist objectAtIndex:i]];
    }
    return arrconvert;
}


//转换json字符串为数组，数组内为字典，对应C#中的DataTable
//转换DataTable实际上就是转换数组
+(NSMutableArray *)hmConvertDataTableFromJsonStr:(NSString *)jsonStr
{
    //NSMutableArray *marrlist=[[NSMutableArray alloc] init];
    
    //首先转换为数组 数据行
    NSMutableArray *rowlist=[self hmConvertArrayFromJsonStr:jsonStr];
    
    return rowlist;
}



//转换json字符串为标准字典_单表表单
+(NSDictionary *)hmConvertFormFromJsonStr:(NSString *)jsonStr{
    NSMutableDictionary *retdict=[[NSMutableDictionary alloc]init];//返回字典
    
    NSDictionary *recdict=[HTFrameNet hmConvertDictFromJsonStr:jsonStr];//接收字典
    
    NSString *recheadtitleStr = [recdict objectForKey:kpFORM_HEAD_TITLE];//单头字段定义 字符串
    NSMutableArray *headDataList=[recdict objectForKey:kpFORM_HEAD_DATA];//单头数据
    
    NSDictionary *headTitleDict=[HTFrameNet hmConvertDictFromTitleStr:recheadtitleStr];//转换为单头定义字典
    
    [retdict setValue:headTitleDict forKey:kpFORM_HEAD_TITLE];//赋值
    [retdict setValue:headDataList forKey:kpFORM_HEAD_DATA];//赋值
    
    
    return retdict;
 
}

//转换json字符串为标准字典_主从表表单
+(NSMutableDictionary *)hmConvertFormDtsFromJsonStr:(NSString *)jsonStr{
    NSMutableDictionary *retdict=[[NSMutableDictionary alloc]init];//返回字典
    
    NSDictionary *recdict=[HTFrameNet hmConvertDictFromJsonStr:jsonStr];//接收字典
    
    NSString *recheadtitleStr = [recdict objectForKey:kpFORM_HEAD_TITLE];//单头字段定义 字符串
    NSMutableArray *headDataList=[recdict objectForKey:kpFORM_HEAD_DATA];//单头数据
    NSString *recdetailtitleStr = [recdict objectForKey:kpFORM_DETAIL_TITLE];//单据明细字段定义 字符串
    NSMutableArray *detailDataList=[recdict objectForKey:kpFORM_DETAIL_DATA];//单据明细数据
    
    NSDictionary *headTitleDict=[HTFrameNet hmConvertDictFromTitleStr:recheadtitleStr];//转换为单头定义字典
    NSDictionary *detailTitleDict=[HTFrameNet hmConvertDictFromTitleStr:recdetailtitleStr];//转换为单据明细定义字典

    [retdict setValue:headTitleDict forKey:kpFORM_HEAD_TITLE];//赋值
    [retdict setValue:headDataList forKey:kpFORM_HEAD_DATA];//赋值
    [retdict setValue:detailTitleDict forKey:kpFORM_DETAIL_TITLE];//赋值
    [retdict setValue:detailDataList forKey:kpFORM_DETAIL_DATA];//赋值
    
    
    return retdict;
}




@end
